package tjs.org.springLoader.reloader;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * Created by Nicky.Tang on 2021/9/29 11:40 下午
 *
 * @since 02.12.10
 */
public class IocReloader implements IReloader, ApplicationContextAware, InitializingBean {

    public static final AnnotationBeanNameGenerator INSTANCE = new AnnotationBeanNameGenerator();

    private ApplicationContext applicationContext;
    private DefaultListableBeanFactory defaultListableBeanFactory;

    @Override
    public boolean isReloader(Class<?> changeClass) {
        return changeClass.getAnnotation(Service.class) != null;
    }

    @Override
    public void reloaderBefore(Class<?> oldClass) {
        //移除ioc中的bean
        String beanName = applicationContext.getBeanNamesForType(oldClass)[0];//todo 处理特殊定义的beanName
        this.defaultListableBeanFactory.removeBeanDefinition(beanName);
    }

    @Override
    public void reloaderAfter(Class<?> newClass) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(newClass);
        String beanName = IocReloader.INSTANCE.generateBeanName(beanDefinitionBuilder.getBeanDefinition(), this.defaultListableBeanFactory);
        this.defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
    }

    @Override
    public int getOrder() {
        //IocReloader应该最先被加载
        return HIGHEST_PRECEDENCE;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
    }
}
